contents

오랜만에 정규식을 쓸 일이 있었는데 이 참에 간단하게 정리하는 시간을 가져보겠습니다. 외우면 참 편한데 결국 못 외우는...


1. 기본 개념


2. 정규표현식의 구조 및 동작 방식


3. 주요 문법 요소

A. 리터럴 문자

B. 메타문자(특수문자)

메타문자 의미 예시
. 임의의 한 문자와 일치 a.c (abc, acc, etc)
^ 문자열의 시작 ^Hi ("Hi there")
$ 문자열의 끝 end$ ("the end")
* 바로 앞 문자가 0회 이상 반복 ab* (a, ab, abb, etc)
+ 바로 앞 문자가 1회 이상 반복 go+ (go, goo, gooo)
? 바로 앞 문자가 0회 또는 1회 colou?r (color, colour)
[] 문자 집합 [aeiou] (모음 중 하나)
` ` OR, 선택
() 그룹화, 캡처 (ab)+
{n,m} 반복 횟수 지정 \d{2,4} (2~4자리 숫자)
\ 이스케이프 \. (진짜 점)

C. 문자 클래스와 단축형

기호 의미
\d 숫자(0~9)
\w 단어 문자(영문자, 숫자, _)
\s 공백 문자
\D 숫자가 아닌 것
\W 단어 문자가 아닌 것
\S 공백이 아닌 것

D. 앵커(Anchors)와 경계

E. Lookahead, Lookbehind (고급)


4. 활용 사례와 예시

1. 이메일 주소 검증

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b

2. 전화번호/숫자 추출

\d{3}-\d{4}-\d{4}

3. 조건 검색·치환

4. 그룹/캡처 활용

(\d{4})-(\d{2})-(\d{2})

5. 프로그래밍 사용 예

Java 예시

import java.util.regex.*;
Pattern p = Pattern.compile("\\d+"); // 숫자 하나 이상
Matcher m = p.matcher("abc123de45f");
while (m.find()) {
    System.out.println(m.group()); // 123, 45
}

Python 예시

import re
result = re.findall(r"\b[\w.%+-]+@[\w.-]+\.\w{2,}\b", text)

6. 주의사항과 고급 활용


7. 베스트 프랙티스


요약

정규표현식은 다양한 환경에서 텍스트의 검색/검증/추출/변환을 효율적으로 처리하는 강력한 도구입니다. 기본 패턴부터 고급 기능까지 이해하면 복잡한 문자열 처리 업무를 매우 짧고 효율적인 코드로 해결할 수 있습니다.


자바에서 자주 쓰이는 정규식을 알아보겠습니다!


1. 숫자 추출/검증

Pattern p = Pattern.compile("\\d+"); // 숫자 하나 이상
Matcher m = p.matcher("abc123de45f");
while (m.find()) {
    System.out.println(m.group()); // 출력: 123, 45
}

문자열에서 모든 숫자 부분 추출.


2. 이메일 주소 검증

String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
System.out.println("test@example.com".matches(emailPattern)); // true

기본 이메일 형식에 맞는지 확인.


3. 전화번호 패턴(미국형식)

String phonePattern = "^\\d{3}-\\d{3}-\\d{4}$";
System.out.println("123-456-7890".matches(phonePattern)); // true

“123-456-7890” 형식의 전화번호 검증.


4. 날짜(YYYY-MM-DD)

String datePattern = "^\\d{4}-\\d{2}-\\d{2}$";
System.out.println("2022-07-31".matches(datePattern)); // true

“yyyy-MM-dd” 형식의 날짜 검증.


5. 정수(부호 가능)

String intPattern = "^[+-]?\\d+$";
System.out.println("-42".matches(intPattern)); // true

정수 입력에서 + 또는 - 부호 가능.


6. 영문/숫자만 입력(아이디, 비밀번호)

String alphaNumPattern = "^[a-zA-Z0-9]+$";
System.out.println("User123".matches(alphaNumPattern)); // true

영문자와 숫자만 포함된 문자열 검증.


7. 공백 기준 분할

Pattern splitPattern = Pattern.compile("\\s+");
String[] words = splitPattern.split("one two\tthree\nfour");
for (String s : words) {
    System.out.println(s); // one, two, three, four
}

공백(스페이스, 탭, 줄바꿈 등)으로 텍스트 분할.


8. 단어 경계 검색(예: “cat”이라는 독립 단어)

Pattern wordPattern = Pattern.compile("\\bcat\\b");
Matcher w = wordPattern.matcher("A cat and a catalog.");
while (w.find()) {
    System.out.println("cat found at: " + w.start());
}

다른 단어 안에 포함된 경우 제외하고 독립적인 단어만 검색.


9. 모음 대체(치환)

Pattern vowels = Pattern.compile("[aeiouAEIOU]");
Matcher vm = vowels.matcher("Hello World!");
String noVowels = vm.replaceAll("_");
System.out.println(noVowels); // H_ll_ W_rld!

패턴 검색 및 대체(치환) 처리.


10. OR 패턴(복수 선택)

Pattern orPattern = Pattern.compile("dog|cat");
Matcher om = orPattern.matcher("My dog and cat are here.");
while (om.find()) {
    System.out.println(om.group()); // dog, cat
}

“dog” 또는 “cat”과 일치하는 모든 경우 검색.


요약표

용도 패턴 입력 예시
숫자 추출/검증 \\d+ abc123de45f
이메일 ^[A-Za-z0-9+_.-]+@...$ test@exam.com
전화번호(미국) ^\\d{3}-\\d{3}-\\d{4}$ 123-456-7890
날짜(YYYY-MM-DD) ^\\d{4}-\\d{2}-\\d{2}$ 2022-07-31
정수(+/-부호) ^[+-]?\\d+$ -42, +5, 0
영문/숫자 ^[a-zA-Z0-9]+$ User123
공백 분할 \\s+ a b\tc\nd
단어 경계 \\bcat\\b cat, catalog
모음 치환 [aeiouAEIOU] Hello World
OR 패턴 `dog cat`

이 패턴들은 자바에서 문자열 검증, 파싱, 변환 등에 가장 빈번하게 활용되는 실무 예시입니다.


이번에는 자바스크립트에서 자주 쓰이는 정규식을 찾아보겠습니다.


1. 숫자 추출

const pattern = /\d+/g;
const str = "내 번호는 12345이고 ID는 6789입니다.";
console.log(str.match(pattern)); // ["12345", "6789"]

문자열에서 연속된 숫자를 모두 찾음.


2. 이메일 주소 검증

const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
console.log(emailPattern.test("test@example.com")); // true

기본적인 이메일 형식 검사.


3. 미국식 전화번호

const phonePattern = /^\d{3}-\d{3}-\d{4}$/;
console.log(phonePattern.test("123-456-7890")); // true

“123-456-7890” 형태의 전화번호 검증.


4. 날짜(YYYY-MM-DD)

const datePattern = /^\d{4}-\d{2}-\d{2}$/;
console.log(datePattern.test("2022-07-31")); // true

ISO 스타일 날짜 형식 확인.


5. 영문자 및 숫자만 허용

const alphaNumPattern = /^[a-zA-Z0-9]+$/;
console.log(alphaNumPattern.test("User123")); // true

영문자와 숫자로만 구성된 문자열만 허용.


6. 단어 경계 찾기

const wordPattern = /\bcat\b/g;
const str = "고양이와 catalog.";
console.log(str.match(wordPattern)); // ["cat"]

단어 ‘cat’만 찾고 ‘catalog’ 내 ‘cat’ 는 제외.


7. 모음 치환

const vowels = /[aeiouAEIOU]/g;
const str = "Hello World!";
const noVowels = str.replace(vowels, "_");
console.log(noVowels); // "H_ll_ W_rld!"

모음을 모두 언더스코어(_)로 대체.


8. 공백 기준 분리

const str = "one two\tthree\nfour";
const words = str.split(/\s+/);
console.log(words); // ["one", "two", "three", "four"]

스페이스, 탭, 줄바꿈 등 모든 공백문자로 분리.


9. OR 조건(복수 선택)

const orPattern = /dog|cat/g;
const str = "나의 개와 고양이.";
console.log(str.match(orPattern)); // ["dog", "cat"]

“dog” 또는 “cat” 둘 중 하나라도 포함 여부 검색.


10. 비밀번호 패턴 (8자리 이상, 숫자 포함, 특수문자 포함)

const pwdPattern = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(pwdPattern.test("Pass@123")); // true

복잡한 비밀번호 조건 검사.


11. URL 검사

const urlPattern = /https?:\/\/(www\.)?\S+\.\S+/;
console.log(urlPattern.test("https://example.com/")); // true

웹 주소 형식 검증.


요약표

용도 패턴 예시 입력
숫자 /\d+/g "ID: 12345"
이메일 /^[A-Za-z0-9._%+-]+@...$/ "test@example.com"
전화번호(미국식) /^\d{3}-\d{3}-\d{4}$/ "123-456-7890"
날짜(YYYY-MM-DD) /^\d{4}-\d{2}-\d{2}$/ "2022-07-31"
영숫자 조합 /^[a-zA-Z0-9]+$/ "User123"
단어 경계 /\bcat\b/g "cat, catalog"
모음 치환 /[aeiouAEIOU]/g "Hello World"
공백 분할 /\s+/ "a b\tc\nd"
OR 조건 `/dog cat/g`
비밀번호 복잡성 /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&]).../ "Pass@123"
URL /https?:\/\/(www\.)?\S+\.\S+/ "https://example.com"

위 패턴은 자바스크립트 개발 시 자주 사용되는 문자열 검증, 검색, 치환 등의 주요 예제입니다.

references